package tech.bmatch.meituan.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tech.bmatch.meituan.model.Merchant;
import tech.bmatch.meituan.service.MerchantService;

import java.io.File;
import java.io.IOException;
import java.util.Set;

public abstract class MerchantFileStoreServiceImpl implements MerchantService {

    private static ObjectMapper objectMapper = new ObjectMapper();
    private static File file = new File("./data.json");
    private static final Logger logger = LoggerFactory.getLogger(MerchantFileStoreServiceImpl.class);

    @Before
    public void initTest() {
        System.out.println("测试init()");
    }

    @Override
    @Test
    public void init() {

        if (!file.exists()) {
            return;
        }
        try {
            Set<Merchant> merchantList = objectMapper.readValue(file, new TypeReference<Set<Merchant>>() {
            });
            for (Merchant merchant : merchantList) {
                add(merchant);
            }
        } catch (IOException e) {
            logger.error("", e);
        }
    }

    public void store(Set<Merchant> merchants) {
        if (merchants == null) {
            return;
        }
        try {
            objectMapper.writeValue(file, merchants);
        } catch (IOException e) {
            logger.error("", e);
        }

    }
}
